package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        // 检验参数：从线程中获取user对象
        ApUser user = AppThreadLocalUtils.getUser();

        // 查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());

        // 判断行为实体是否为空
        if (apBehaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实体行为不存在");
        }

        // 查询指定文章阅读行为是否存在
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        // 判断为空则不存在
        if (readBehavior == null) {
            //  设置新的参数
            readBehavior = new ApReadBehavior();
            readBehavior.setCreatedTime(new Date());
            readBehavior.setCount((short) 1);
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setEntryId(apBehaviorEntry.getId());
            readBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(readBehavior);
        } else {
            // 不为空直接更新阅读次数
            readBehavior.setCount((short) (readBehavior.getCount() + 1));
            mongoTemplate.save(readBehavior);
        }
        return ResponseResult.okResult();
    }
}
